﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Commons.ASPNETCore
{
    /// <summary>
    /// 枚举扩展
    /// </summary>
    public static class EnumException
    {
        private static ConcurrentDictionary<Enum, string> _ConcurrentDictionary = new();
        /// <summary>
        /// 获取枚举的描述信息(Descripion)。
        /// 支持位域，如果是位域组合值，多个按分隔符组合。
        /// </summary>
        public static string GetDescription(this Enum enumeration)
        {
            return _ConcurrentDictionary.GetOrAdd(enumeration, (key) =>
            {
                var type = key.GetType();
                var field = type.GetField(key.ToString());
                //如果field为null则应该是组合位域值，
                return field == null ? key.GetDescriptions() : GetDescription(field);
            });
        }
        /// <summary>
        /// 获取位域枚举的描述，多个按分隔符组合
        /// </summary>
        private static string GetDescriptions(this Enum enumeration, string separator = ",")
        {
            var names = enumeration.ToString().Split(',');
            string[] res = new string[names.Length];
            var type = enumeration.GetType();
            for (int i = 0; i < names.Length; i++)
            {
                var field = type.GetField(names[i].Trim());
                if (field == null) continue;
                res[i] = GetDescription(field);
            }
            return string.Join(separator, res);
        }

        private static string GetDescription(FieldInfo field)
        {
            var att = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
            return att == null ? field.Name : ((DescriptionAttribute)att).Description;
        }
    }
}
